import type { AxiosRequestConfig, AxiosError } from 'axios';
import axios, { AxiosResponse } from 'axios';
import { localStorage } from '@/utils/local-storage';
import { notification, message } from 'ant-design-vue';
import { STORAGE_TOKEN_KEY } from '@/store/app';
import { loginRoutePath } from '@/router/define-meta';
import ls from '@/utils/local-storage';
import { useRoute } from 'vue-router';

// 这里是用于设定请求后端时，所用的 Token KEY
// 可以根据自己的需要修改，常见的如 Access-Token，Authorization
// 需要注意的是，请尽量保证使用中横线`-` 来作为分隔符，
// 避免被 nginx 等负载均衡器丢弃了自定义的请求头
export const REQUEST_TOKEN_KEY = 'Authorization';
const route = useRoute();
// 创建 axios 实例
const request = axios.create({
    // API 请求的默认前缀
    baseURL: process.env.VUE_APP_API_BASE_URL,
    timeout: 180 * 1000, // 请求超时时间
});
export type RequestError = AxiosError<{
    response: {
        msg?: string;
        code: number;
        data?: any;
    };
}>;
// 异常拦截处理器
const errorHandler = (error: RequestError): Promise<any> => {
    console.log(error);

    if (error.response) {
        const { data, status, statusText } = error.response;
        // 403 无权限
        if (status === 403) {
            notification.error({
                message: 'Forbidden',
                description: (data && data?.msg) || statusText,
            });
        }
        // 401 424 未登录/未授权
        if ([401, 424].includes(status)) {
            ls.set(STORAGE_TOKEN_KEY, undefined);
            ls.set('STORAGE_USER_ID', undefined);
            notification.error({
                message: data?.msg || 'Authorization verification failed',
            });
            console.log(route, location);
            // 如果你需要直接跳转登录页面

            if (!location.pathname.includes('login')) location.replace(`${process.env.VUE_APP_PUBLIC_PATH} + ${loginRoutePath}`.replaceAll('//', '/'));
        }
    }
    return Promise.reject(error);
};

// 请求拦截器
const requestHandler = (config: AxiosRequestConfig): AxiosRequestConfig | Promise<AxiosRequestConfig> => {
    const savedToken = localStorage.get(STORAGE_TOKEN_KEY);
    // 如果 token 存在
    // 让每个请求携带自定义 token, 请根据实际情况修改
    if (savedToken && !config.url.includes('/oauth2/token') && !config.url.includes('/oauth2/revoke')) {
        config.headers[REQUEST_TOKEN_KEY] = `Bearer ${savedToken}`;
    }
    return config;
};

// Add a request interceptor
request.interceptors.request.use(requestHandler, errorHandler);

// 响应拦截器
const responseHandler = (response: AxiosResponse<any>) => {
    const {
        status,
        data: { code, data, msg },
        headers,
    } = response;
    // 捕获 302 响应
    if (status === 302) {
        const locationUrl = response.headers['location'];
        if (locationUrl) {
            console.log('重定向 URL:', locationUrl);
            window.open(locationUrl, '_blank'); // 在新标签页打开跳转的 URL
        }
    }
    if (status === 200) {
        if (headers['content-type'].includes('application/vnd.ms-excel')) {
            return response.data;
        } else if (headers['content-type'].includes('application/zip')) {
            return response;
        } else {
            if (code == 302) {
                window.open(response.data.data);
            } else {
                if (code == 200) {
                    return response.data;
                } else {
                    message.error(msg || '请求失败，请联系管理员');
                    return false;
                }
            }
        }
    } else {
        notification.error({
            message: '请求失败',
        });
    }
};

// Add a response interceptor
request.interceptors.response.use(responseHandler, errorHandler);

export { AxiosResponse };

export default request;
